package it.espsoft.easysuperenalotto.logic;

import it.espsoft.easysuperenalotto.bean.EstrazioneBean;
import it.espsoft.easysuperenalotto.dao.EstrazioneDAO;
import it.espsoft.easysuperenalotto.utils.Utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Spanned;

public class RetrieveEstrazioniThread extends Thread {
	private Handler handler = null;
	
	public RetrieveEstrazioniThread(Handler handler){
		this.handler = handler;
	}
	
	public static String DownloadText(String strUrl) throws IOException, URISyntaxException{
		BufferedReader in = null;
		String page = "";
        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet();
            //request.setHeader("Connection", "keep-alive");
            request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            //request.setHeader("Accept-Language", "it-it,it;q=0.8,en-us;q=0.5,en;q=0.3");
            //request.setHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
            
            request.setURI(new URI(strUrl));
            HttpResponse response = client.execute(request);
            in = new BufferedReader
            (new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            page = sb.toString();
            } finally {
            if (in != null) {
                try {
                    in.close();
                    } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return page;
	}
	@Override
	public void run() {
		ArrayList<EstrazioneBean> listaEstrazioni = new ArrayList<EstrazioneBean>();
		try {
			  String htmlTxt = "";
			  int page = 1;
			  boolean finish = false;
			  do{
				  htmlTxt = DownloadText("http://giochinumerici.sisal.it/portal/page/portal/SitoGioco_DocLib/Contenuti/BoxInformativo/2011/?pagina="+page);
				  
				  htmlTxt = htmlTxt.substring(htmlTxt.indexOf("<tr class=\"UltimoConcorsoInfo_boxBottom_datiBianco\""));
				  
				  String[] righe = htmlTxt.split("</tr>");
				  
				  for (int i = 0; i < 30; i++) {
					righe[i] = righe[i].substring(righe[i].indexOf("<a "));
					righe[i] = righe[i].replace("</td>", "").replace("</a>", "").replace("\n", "");
					
					String items[] = righe[i].split("<td>");
					
					EstrazioneBean eb = new EstrazioneBean();
					SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
					Date data = sdf.parse(items[1]);
					
					if( "".equals(Utils.normalizeString(items[2])) ){
						finish = true;
						break;
					}
					
					eb.setNumConcorso(new Integer(Utils.normalizeString(items[0].substring(items[0].indexOf(">")+1))));
					eb.setDataConcorso(data);
					eb.setJackpot("");
					eb.setPrimo(Utils.normalizeString(items[2]));
					eb.setSecondo(Utils.normalizeString(items[3]));
					eb.setTerzo(Utils.normalizeString(items[4]));
					eb.setQuarto(Utils.normalizeString(items[5]));
					eb.setQuinto(Utils.normalizeString(items[6]));
					eb.setSesto(Utils.normalizeString(items[7]));
					eb.setJolly(Utils.normalizeString(items[8]));
					eb.setSuperstar(Utils.normalizeString(items[9]));
					listaEstrazioni.add(eb);
				  }
				  page++;
			  }while(!finish);
			  
			  EstrazioneDAO.deleteAllEstrazioni();
			  
			  for (EstrazioneBean eb : listaEstrazioni) {
				  EstrazioneDAO.insert(eb);
			  }
			  
			  URL rssUrl = new URL("http://www.sisal.it/Feed/pubblico/servlet/feed?nome=jackpotSestinaSuperEnalotto");
			  SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
			  SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
			  XMLReader myXMLReader = mySAXParser.getXMLReader();
			  
			  String[] itemsToExtract = {"jackpot","concorso","combinazione"};
			  
			  RSSHandler myRSSHandler = new RSSHandler(itemsToExtract);
			  myXMLReader.setContentHandler(myRSSHandler);
			  InputSource myInputSource = new InputSource(rssUrl.openStream());
			  myXMLReader.parse(myInputSource);
			  Map<String,String> result = myRSSHandler.getStrElements();
			  Spanned jackpot = Html.fromHtml(result.get("jackpot"));
			  Spanned concorso = Html.fromHtml(result.get("concorso"));
			  
			  EstrazioneBean eb = new EstrazioneBean();
			  eb.setJackpot(Utils.normalizeString(jackpot.toString()).split(" ")[2]);
			  eb.setNumConcorso(Integer.parseInt(Utils.normalizeString(concorso.toString()).split(" ")[2]));
			  EstrazioneDAO.updateEstrazioneByConcorso(eb);
			  Message msg = new Message();
			  msg.arg1 = 0;
			  handler.sendMessage(msg);
		 } catch (MalformedURLException e) {
			 e.printStackTrace();
		 } catch (ParserConfigurationException e) {
			 e.printStackTrace();
		 } catch (SAXException e) {
			 e.printStackTrace();
		 } catch (IOException e) {
			 e.printStackTrace();
		 }catch (Exception e) {
			 e.printStackTrace();
		 }		
	}
}
